import { useModel } from "umi";
import { Form, Input, Button, message, Space, Select, Radio } from "antd";
import { useReactive } from "ahooks";
import { useEffect } from "react";

import { UpdateIndustryType } from "../../_graphql/resources";

const EditIndustryType = ({ record, industryTypes, reloadData }) => {
    const { graphqlFetchPlatform, remoteData, BNTApplicationResourceCenterServiceURL } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
        referenceDatabases: [],
        selectedData: null,
    });

    const loadReferenceDatabases = async () => {
        let res = await remoteData({
            object: "bnt-application-resource-center-service",
            serviceUrl: BNTApplicationResourceCenterServiceURL,
            serviceName: "/resource/referenceDatabase/organization/getAll",
            params: {},
        });
        state.referenceDatabases = res || [];
        state.selectedData = res?.find((item) => item.databaseName === record.itRedb);
    };

    useEffect(() => {
        loadReferenceDatabases();
    }, []);

    let onFinish = async (values) => {
        if (!state.selectedData) return onCloseGlobalModal();
        state.loading = true;
        let res = await graphqlFetchPlatform({
            query: UpdateIndustryType,
            variables: {
                ...values,
                itUuid: record.itUuid,
                itDbna: state.selectedData.graphqlServiceName,
                itHbpa: state.selectedData.heartBeatParams,
            },
        });
        if (res) {
            message.success("成功修改信息");
            reloadData();
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    const validator = async (rule, value) => {
        if (value && /^[\u4e00-\u9fa5a-zA-Z0-9]{1,50}$/.test(value)) {
            let index = industryTypes.findIndex((item) => item.itName === value && item.itUuid !== record.itUuid);
            return index === -1 ? Promise.resolve() : Promise.reject("已存在相同的类别名称，请重新输入");
        } else {
            return Promise.reject("只能输入中文、英文、数字，最多50个字符");
        }
    };

    return (
        <div>
            <Form form={form} layout="horizontal" onFinish={onFinish} labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} initialValues={record}>
                <Form.Item label="行业类型名称" name="itName" validateTrigger="onBlur" rules={[{ required: true, validator: validator }]}>
                    <Input />
                </Form.Item>

                <Form.Item label="参考数据库" name="itRedb" rules={[{ required: true, message: "请选择参数数据库" }]}>
                    <Select allowClear options={state.referenceDatabases} fieldNames={{ label: "title", value: "databaseName" }} onChange={(value, option) => (state.selectedData = option)} />
                </Form.Item>

                <Form.Item label="领域类型" name="itType" rules={[{ required: true }]}>
                    <Radio.Group>
                        <Radio value={"public"}>公共领域</Radio>
                        <Radio value={"special"}>特殊领域</Radio>
                    </Radio.Group>
                </Form.Item>

                <div style={{ marginTop: 20, textAlign: "center" }}>
                    <Space>
                        <Button loading={state.loading} type="primary" htmlType="submit">
                            保存
                        </Button>
                        <Button loading={state.loading} onClick={onCloseGlobalModal}>
                            取消
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

export default EditIndustryType;
